package com.ruoyi.system.controller;

import java.util.Arrays;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.constant.ActivityConstant;
import com.ruoyi.common.core.constant.SigninConstants;
import com.ruoyi.common.core.constant.SignupConstants;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.domain.Activity;
import com.ruoyi.system.domain.Signup;
import com.ruoyi.system.service.IActivityService;
import com.ruoyi.system.service.ISignupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.system.domain.Signin;
import com.ruoyi.system.service.ISigninService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 签到表Controller
 * 
 * @author hyb
 * @date 2023-02-13
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("/signin")
public class SigninController extends BaseController
{
    @Autowired
    private ISigninService signinService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private ISignupService signupService;

    @InnerAuth
    @PostMapping("/getInfo")
    public AjaxResult getInfo(@RequestBody Signin signin){
        List<Signin> signins = signinService.selectSigninAllList(signin);
        if(signins.size()==0){
            return AjaxResult.error();
        }
        return AjaxResult.success().put("signIn",signins.get(0));
    }

    /*
    * 查询补签用户
    * */
    @RequiresPermissions("activity:signin:listSubAdd")
    @GetMapping("/listSubAdd")
    public TableDataInfo listSubAdd(@RequestParam("id")String id){

        startPage();
        List<Signin> list = signinService.selectAllSubAddSigninList( id);
        return getDataTable(list);
    }


    /*
    * 后台补签
    * */
    @RequiresPermissions("activity:signin:subAdd")
    @PostMapping("/subAdd")
    public AjaxResult subAdd(@RequestBody Signin signin){
        //必须负责人补签
        Activity activity = activityService.selectActivityById(signin.getActivityId());
        if (activity==null){
            return AjaxResult.error("活动不存在");
        }
        if (!activity.getUserId().equals(SecurityUtils.getUserId())){
            return AjaxResult.error("你不是负责人,无法补签");
        }
        //活动必须开始,或者结束
        Long status = activity.getStatus();
        if (!status.equals(ActivityConstant.STARTING_STATUS)
        && !status.equals(ActivityConstant.LASTED_STATUS)
        ){
            return AjaxResult.error("活动未在开始中或未在结束状态,无法补签");
        }
        //补签的用户必须是已录取的用户
        Signup signup = new Signup();
        signup.setActivityId(activity.getId());
        signup.setUserId(signin.getUserId());
        List<Signup> signups = signupService.selectSignupList(signup);
        if (signups.size()==0){
            return AjaxResult.error("该用户未报名");
        }
        Signup si = signups.get(0);
        if (!si.getStatus().equals(SignupConstants.ADD_STATUS)){
            return AjaxResult.error("该用户未被录取");
        }

        //从活动中获取补签地址
//        signin.setActivityId(activity.getId());
        String position = activity.getPosition();
        String[] split = position.split(",");
        String[] pxy = split[1].split("-");
        signin.setPosition(split[0]);
        signin.setPositionX(pxy[0]);
        signin.setPositionY(pxy[1]);
        signin.setUpdateTime(DateUtils.getNowDate());
        signin.setStatus(SigninConstants.SUCCESS);
        //设置签到方式
        signin.setPf1(String.valueOf(SigninConstants.SUB_SIGN_TYPE));

        return toAjax(signinService.insertSignin(signin));
    }

    /**
     * 查询签到表列表
     */
    @RequiresPermissions("system:signin:list")
    @GetMapping("/list")
    public TableDataInfo list(Signin signin)
    {
        //只能查询活动是自己的
        signin.setPf3(String.valueOf(SecurityUtils.getUserId()));
        startPage();
        List<Signin> list = signinService.selectSigninList(signin);
        return getDataTable(list);
    }

    /**
     * 导出签到表列表
     */
    @RequiresPermissions("system:signin:export")
    @Log(title = "签到表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Signin signin)
    {
        signin.setPf3(String.valueOf(SecurityUtils.getUserId()));
        List<Signin> list = signinService.selectSigninList(signin);
        ExcelUtil<Signin> util = new ExcelUtil<Signin>(Signin.class);
        util.exportExcel(response, list, "签到表数据");
    }

    /**
     * 获取签到表详细信息
     */
    @RequiresPermissions("system:signin:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(signinService.selectSigninById(id));
    }

    /**
     * 新增签到表
     */
    @InnerAuth
    @Log(title = "签到表", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Signin signin)
    {

        return toAjax(signinService.insertSignin(signin));
    }


    /**
     * 修改签到表
     */
    @RequiresPermissions("system:signin:edit")
    @Log(title = "签到表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Signin signin)
    {
        Long activityId = signin.getActivityId();
        Activity activity = activityService.selectActivityById(activityId);
        if (!activity.getUserId().equals(SecurityUtils.getUserId())){
            return AjaxResult.error("该活动非本人创建,无法修改");
        }
        return toAjax(signinService.updateSignin(signin));
    }

    /**
     * 删除签到表
     */
    @RequiresPermissions("system:signin:remove")
    @Log(title = "签到表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for (Long id : ids) {
            Signin signin = signinService.selectSigninById(id);
            Long activityId = signin.getActivityId();
            Activity activity = activityService.selectActivityById(activityId);
            if (!activity.getUserId().equals(SecurityUtils.getUserId())){
                return AjaxResult.error("该活动非本人创建,无法修改");
            }
        }
        return toAjax(signinService.deleteSigninByIds(ids));
    }
}
